/**
 * @author
 * @createtime
 * @class MaterialAllocationForm
 * @extends Ext.Window
 * @description MaterialAllocation表单
 */
MaterialAllocationForm = Ext.extend(Ext.Window, {
	//内嵌FormPanel
	formPanel : null,
	//构造函数
	constructor : function(_cfg) {
		Ext.applyIf(this, _cfg);
		//必须先初始化组件
		this.initUIComponents();
		MaterialAllocationForm.superclass.constructor.call(this, {
			id : 'MaterialAllocationFormWin',
			layout : 'fit',
			items : this.formPanel,
			modal : true,
			width : 780,
			height : 430,
			maximizable : true,
			title : '[物资调拨]详细信息',
			buttonAlign : 'center',
			buttons : this.buttons
		});
	},//end of the constructor
	//初始化组件
	initUIComponents : function() {
		var thizId = this.id;
		var url = __ctxPath + "/system/listDepartment.do?opt=appUser";
		var fromDeptTreeSelector = new TreeSelector("materialAllocation.fromDeptTreeSelector", url, "所属部门", "materialAllocation.fromDept.depId",
		null, 200, "materialAllocationFromDept");
		var toDeptTreeSelector = new TreeSelector("materialAllocation.toDeptTreeSelector", url, "所属部门", "materialAllocation.toDept.depId", false,
		200, "materialAllocationToDept");
		this.formPanel = new Ext.FormPanel({
			layout : 'form',
			trackResetOnLoad : true,
			bodyStyle : 'padding:10px 10px 10px 10px',
			border : false,
			url : __ctxPath + '/produce/saveMaterialAllocation.do',
			id : 'MaterialAllocationForm',
			defaults : {
				anchor : '98%,98%'
			},
			defaultType : 'textfield',
			items : [{
						name : 'materialAllocation.id',
						id : 'id',
						xtype : 'hidden',
						value : this.id == null ? '' : this.id
					},{
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '调出部门：',
								width : 90
							}, fromDeptTreeSelector, {
								xtype : "hidden",
								name : "materialAllocation.fromDept.depId",
								id : "materialAllocation.fromDept.depId"
							}, {
								text : '经办人：',
								style : 'margin-left:10px;',
								width : 60
							}, {
								xtype : 'textfield',
								name : 'materialAllocationOperator',
								id : 'materialAllocationOperator',
								readOnly : true,
								emptyText : '请选择经办人',
								width : 120,
								listeners : {
									focus : function() {
										UserSelector.getView(function(ids, names) {
											Ext.getCmp("materialAllocationOperator").setValue(names);
											Ext.getCmp("materialAllocation.operator.userId").setValue(ids);
										}, true).show();
									}
								}
							}, {
								xtype : "hidden",
								name : "materialAllocation.operator.userId",
								id : "materialAllocation.operator.userId"
							}, {
								text : '调出日期：',
								style : 'margin-left:10px;',
								width : 60
							}, {
								xtype : 'datefield',
								name : 'materialAllocation.fromDate',
								id : 'ate',
								format : 'Y-m-d',
								value : new Date()
							}]
				}, {
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '调入部门：',
								width : 90
							}, toDeptTreeSelector, {
								xtype : "hidden",
								name : "materialAllocation.toDept.depId",
								id : "materialAllocation.toDept.depId"
							}, {
								text : '接收人：',
								style : 'margin-left:10px;',
								width : 60
							}, {
								xtype : 'textfield',
								name : 'materialAllocationReceiverUser',
								id : 'materialAllocationReceiverUser',
								readOnly : true,
								emptyText : '请选择接收人',
								width : 120,
								listeners : {
									focus : function() {
										UserSelector.getView(function(ids, names) {
											Ext.getCmp("materialAllocationReceiverUser").setValue(names);
											Ext.getCmp("materialAllocation.receiverUser.userId").setValue(ids);
										}, true).show();
									}
								}
							}, {
								xtype : "hidden",
								name : "materialAllocation.receiverUser.userId",
								id : "materialAllocation.receiverUser.userId"
							}, {
								text : '接收日期：',
								style : 'margin-left:10px;',
								width : 60
							}, {
								xtype : 'datefield',
								name : 'materialAllocation.toDate',
								id : 'e',
								format : 'Y-m-d',
								value : new Date()
							}]
				}, {
					xtype : 'container',
					layout : 'column',
					height : 65,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [ {
								text : '调拨原因：',
								width : 90
							}, {
								xtype : 'textarea',
								name : 'materialAllocation.reason',
								id : 'reason',
								height : 60,
								columnWidth:.86
							}]
				}, {
					xtype : 'container',
					layout : 'column',
					height : 25,
					defaults : {
						xtype : 'label',
						style : {
							margin : '0px 0px 3px 0px'
						}
					},
					items : [{
								text : '物资调拨详情：'
							}, {
								style : 'color:red',
								id : 'materialAllocationErrorLabel',
								text : '(*必填)'
							}]
				}, {
					xtype : 'container',
					style : 'padding-left:0px;margin-bottom:10px',
					layout : 'column',
					items : [{
								name : 'resultGridData',
								xtype : 'hidden',
								id : 'materialAllocation.resultGridData'
							}, {
								name : 'dataList',
								xtype : 'hidden',
								id : 'materialAllocation.dataList'
							}, {
								xtype : 'grid',
								id : 'materialAllocation.resultGridDataGrid',
								height : 220,
								width : '98%',
								stripeRows : true,
								trackMouseOver : true,
								clicksToEdit : 1,
								plugins : [new Ext.ux.grid.RowEditor({
									saveText : '保存',
									cancelText : '取消',
									errorText : '请输入完整信息',
									errorSummary : false
								})],
								store : new Ext.data.JsonStore({
									url : __ctxPath + '/produce/listMaterialAllocationInfo.do',
									root : 'result',
									totalProperty : 'totalCounts',
									remoteSort : true,
									fields : ['id', {
												name : 'materialId',
												mapping : 'material.id'
											}, {
												name : 'materialNo',
												mapping : 'material.materialNo'
											}, {
												name : 'materialName',
												mapping : 'material.materialName'
											}, 'detail','unit', 'num', 'preUnitPrice', 'preTotal', 'remark'],
									listeners : {
										'update' : function(value) {
											var r = this.getRange();
											var resultArray = [];
											var jsonArr = [];
											var sum = 0;
											var rlen = r.length;
											for (var i = 0; i < rlen; i++) {
												resultArray.push([]);
												if (r[i].fields) {
													var fields = r[i].fields;
													var flen = fields.length;
													var obj = {
														id : null,
														material : {
															id : ''
														},
														detail : '',
														unit : '',
														num : '',
														preUnitPrice : '',
														preTotal : '',
														remark : ''
													}
													for (var z = 0; z < flen; z++) {
														var fieldValue = r[i].get(fields.keys[z]);
														if (Ext.isEmpty(fieldValue) || fieldValue == '请双击选择' || fieldValue == '请双击填写') {
															continue;
														}
														if (fields.keys[z] == 'id') {
															if (fieldValue != '') {
																obj.id = fieldValue;
															}
														} else if (fields.keys[z] == 'materialId') {
															obj.material.id = fieldValue;
														} else if (fields.keys[z] == 'materialNo') {
															resultArray[i].push('物资编号:' + fieldValue);
														} else if (fields.keys[z] == 'materialName') {
															resultArray[i].push('物资名称:' + fieldValue);
														} else if (fields.keys[z] == 'detail') {
															resultArray[i].push('详细描述:' + fieldValue);
															obj.detail = fieldValue;
														} else if (fields.keys[z] == 'unit') {
															resultArray[i].push('单位:' + fieldValue);
															obj.unit = fieldValue;
														} else if (fields.keys[z] == 'num') {
															resultArray[i].push('数量:' + fieldValue);
															obj.num = fieldValue;
														} else if (fields.keys[z] == 'preUnitPrice') {
															resultArray[i].push('单价估算:' + fieldValue);
															obj.preUnitPrice = fieldValue;
														} else if (fields.keys[z] == 'preTotal') {
															resultArray[i].push('合价估价:' + fieldValue);
															obj.preTotal = fieldValue;
														} else if (fields.keys[z] == 'remark') {
															resultArray[i].push('备注:' + fieldValue + ";");
															obj.remark = fieldValue;
														}
													}
													jsonArr.push(obj);
												}
											}
											//删除空元素
											for (var i = 0; i < resultArray.length; i++) {
												if (resultArray[i].length == 0) {
													resultArray.splice(i, 1);
													i--;
												}
											}
											Ext.getCmp('materialAllocation.resultGridData').setValue(resultArray);
											Ext.getCmp('materialAllocation.dataList').setValue(Ext.util.JSON.encode(jsonArr));
										}
									}
								}),
								cm : new Ext.grid.ColumnModel({
									columns : [new Ext.grid.RowNumberer(), {
												dataIndex : 'id',
												width : 50,
												hidden : true
											}, {
												dataIndex : 'materialId',
												width : 0,
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													id : 'materialAllocationInfo.materialId',
													maxLength : 64
												}))
											}, {
												header : '物资编号',
												dataIndex : 'materialNo',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													allowBlank : false,
													id : 'materialAllocationInfo.materialNo',
													maxLength : 64,
													allowBlank : false,
													readOnly : true,
													emptyText : '请选择物资',
													listeners : {
														'focus' : function() {
															MaterialSelector.getView(function(materialIds, materialNos, materialNames) {
																Ext.getCmp("materialAllocationInfo.materialId").setValue(materialIds);
																Ext.getCmp("materialAllocationInfo.materialNo").setValue(materialNos);
																Ext.getCmp("materialAllocationInfo.materialName").setValue(materialNames);
															}, true).show();
														}
													}
												}))
											}, {
												header : '物资名称',
												dataIndex : 'materialName',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													allowBlank : false,
													id : 'materialAllocationInfo.materialName',
													maxLength : 64,
													allowBlank : false,
													readOnly : true,
													emptyText : '请选择物资',
													listeners : {
														'focus' : function() {
															MaterialSelector.getView(function(materialIds, materialNos, materialNames) {
																Ext.getCmp("materialAllocationInfo.materialId").setValue(materialIds);
																Ext.getCmp("materialAllocationInfo.materialNo").setValue(materialNos);
																Ext.getCmp("materialAllocationInfo.materialName").setValue(materialNames);
															}, true).show();
														}
													}
												}))
											}, {
												header : '详细描述',
												dataIndex : 'detail',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													id : 'materialAllocationInfo.detail',
													allowBlank : false
												}))
											}, {
												header : '单位',
												dataIndex : 'unit',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													allowBlank : false,
													id : 'materialAllocationInfo.unit',
													maxLength : 64
												}))
											}, {
												header : '数量',
												dataIndex : 'num',
												editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
													id : 'materialAllocationInfo.num',
													allowBlank : false,
													maxLength : 9,
													enableKeyEvents : true,
													listeners : {
														keyup : function() {
															var num = Ext.getCmp('materialAllocationInfo.num').getValue();
															var preUnitPrice = Ext.getCmp('materialAllocationInfo.preUnitPrice').getValue();
															if (!Ext.isEmpty(preUnitPrice)) {
																Ext.getCmp('materialAllocationInfo.preTotal').setValue(preUnitPrice * num);
															}
														}
													}
												}))
											}, {
												header : '单价估算',
												dataIndex : 'preUnitPrice',
												editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
													id : 'materialAllocationInfo.preUnitPrice',
													allowBlank : false,
													maxLength : 9,
													regex : /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
													regexText : '请输入正确格式的金额',
													enableKeyEvents : true,
													listeners : {
														keyup : function() {
															var num = Ext.getCmp('materialAllocationInfo.num').getValue();
															var preUnitPrice = Ext.getCmp('materialAllocationInfo.preUnitPrice').getValue();
															if (!Ext.isEmpty(num)) {
																Ext.getCmp('materialAllocationInfo.preTotal').setValue(preUnitPrice * num);
															}
														}
													}
												}))
											}, {
												header : '合价估价',
												dataIndex : 'preTotal',
												editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
													id : 'materialAllocationInfo.preTotal',
													readOnly : true,
													maxLength : 10,
													emptyText : '系统自动生成'
												}))
											}, {
												header : '备注',
												dataIndex : 'remark',
												editor : new Ext.grid.GridEditor(new Ext.form.TextField({
													id : 'materialAllocationInfo.remark'
												})),
												width : 150
											}],
									defaults : {
										sortable : false,
										menuDisabled : false,
										width : 100
									}
								}),
								tbar : new Ext.Toolbar({
									height : 30,
									items : [{
												iconCls : 'btn-add',
												text : '添加',
												xtype : 'button',
												handler : function() {
													var DataRecord = Ext.data.Record.create([{
																name : 'id'
															}, {
																name : 'materialId'
															}, {
																name : 'materialNo'
															}, {
																name : 'materialName'
															}, {
																name : 'detail'
															}, {
																name : 'unit'
															}, {
																name : 'num'
															}, {
																name : 'preUnitPrice'
															}, {
																name : 'preTotal'
															}, {
																name : 'remark'
															}]);
													var store = Ext.getCmp('materialAllocation.resultGridDataGrid').store;
													var grid = Ext.getCmp('materialAllocation.resultGridDataGrid');

													var n1 = '';

													var newRowData = {
														materialId : n1,
														materialNo : n1,
														materialName : n1,
														detail : n1,
														unit : n1,
														num : n1,
														preUnitPrice : n1,
														preTotal : n1,
														remark : n1
													};
													var newRecord = new DataRecord(newRowData);
													store.add([newRecord]);

													grid.getSelectionModel().on('selectionchange', function(sm) {
														Ext.getCmp('materialAllocation.removeBtn').setDisabled(sm.getCount() < 1);
													});
												}
											}, {
												iconCls : 'btn-del',
												text : '删除',
												id : 'materialAllocation.removeBtn',
												xtype : 'button',
												handler : function() {
													var store = Ext.getCmp('materialAllocation.resultGridDataGrid').store;
													var grid = Ext.getCmp('materialAllocation.resultGridDataGrid');
													var s = grid.getSelectionModel().getSelections();
													for (var i = 0, r; r = s[i]; i++) {
														store.remove(r);
													}
													store.fireEvent("update");//更新事件
												}
											}]
								})
							}]
				}, {
					xtype : 'textfield',
					hidden : true,
					validator : function() {
						var resultGridData = Ext.getCmp('materialAllocation.resultGridData').getValue();
						var errorLabel = Ext.getCmp("materialAllocationErrorLabel");
						if (Ext.isEmpty(thizId)) {
							if (Ext.isEmpty(resultGridData)) {//为空显示提示
								errorLabel.setText('请填写报废处理详情');
								return false;
							}
						}
						return true
					}
				}]
		});
		//加载表单对应的数据	
		this.initData();
		//初始化功能按钮
		this.buttons = [{
					text : '保存',
					iconCls : 'btn-save',
					handler : this.save.createCallback(this.formPanel, this)
				}, {
					text : '重置',
					iconCls : 'btn-reset',
					handler : this.reset.createCallback(this.formPanel)
				}, {
					text : '取消',
					iconCls : 'btn-cancel',
					handler : this.cancel.createCallback(this)
				}];
	},//end of the initcomponents
	/**
	 * 初始化数据
	 * 
	 * @param {}
	 *            formPanel
	 */
	initData : function() {
		//加载表单对应的数据	
		if (this.id != null && this.id != 'undefined') {
			Ext.getCmp('materialAllocation.resultGridDataGrid').getStore().load({params:{
					'Q_materialAllocation.id_L_EQ':this.id,
					start:0,
					limit:9999
			}});
			this.formPanel.getForm().load({
				deferredRender : false,
				url : __ctxPath + '/produce/getMaterialAllocation.do?id=' + this.id,
				waitMsg : '正在载入数据...',
				success : function(form, action) {
					var jsonData = Ext.util.JSON.decode(action.response.responseText);
					var res = jsonData.data;
					if (!Ext.isEmpty(res.fromDept)) {
						Ext.getCmp("materialAllocation.fromDeptTreeSelector").setValue(res.fromDept.depName);
						Ext.getCmp("materialAllocation.fromDeptTreeSelector").originalValue = res.fromDept.depName;
						Ext.getCmp("materialAllocation.fromDept.depId").setValue(res.fromDept.depId);
						Ext.getCmp("materialAllocation.fromDept.depId").originalValue = res.fromDept.depId;
					}
					if (!Ext.isEmpty(res.operator)) {
						Ext.getCmp("materialAllocationOperator").setValue(res.operator.fullname);
						Ext.getCmp("materialAllocationOperator").originalValue = res.operator.fullname;
						Ext.getCmp("materialAllocation.operator.userId").setValue(res.operator.userId);
						Ext.getCmp("materialAllocation.operator.userId").originalValue = res.operator.userId;
					}
					if (!Ext.isEmpty(res.toDept)) {
						Ext.getCmp("materialAllocation.toDeptTreeSelector").setValue(res.toDept.depName);
						Ext.getCmp("materialAllocation.toDeptTreeSelector").originalValue = res.toDept.depName;
						Ext.getCmp("materialAllocation.toDept.depId").setValue(res.toDept.depId);
						Ext.getCmp("materialAllocation.toDept.depId").originalValue = res.toDept.depId;
					}
					if (!Ext.isEmpty(res.receiverUser)) {
						Ext.getCmp("materialAllocationReceiverUser").setValue(res.receiverUser.fullname);
						Ext.getCmp("materialAllocationReceiverUser").originalValue = res.receiverUser.fullname;
						Ext.getCmp("materialAllocation.receiverUser.userId").setValue(res.receiverUser.userId);
						Ext.getCmp("materialAllocation.receiverUser.userId").originalValue = res.receiverUser.userId;
					}
					//Ext.getCmp("").originalValue=
				},
				failure : function(form, action) {
				}
			});
		}
	},
	/**
	 * 重置
	 * 
	 * @param {}
	 *            formPanel
	 */
	reset : function(formPanel) {
		formPanel.getForm().reset();
	},
	/**
	 * 取消
	 * 
	 * @param {}
	 *            window
	 */
	cancel : function(window) {
		window.close();
	},
	/**
	 * 保存记录
	 */
	save : function(formPanel, window) {
		if (formPanel.getForm().isValid()) {
			formPanel.getForm().submit({
				method : 'POST',
				waitMsg : '正在提交数据...',
				success : function(fp, action) {
					Ext.ux.Toast.msg('操作信息', '成功保存信息！');
					var gridPanel = Ext.getCmp('MaterialAllocationGrid');
					if (gridPanel != null) {
						gridPanel.getStore().reload();
					}
					window.close();
				},
				failure : function(fp, action) {
					Ext.MessageBox.show({
						title : '操作信息',
						msg : '信息保存出错，请联系管理员！',
						buttons : Ext.MessageBox.OK,
						icon : Ext.MessageBox.ERROR
					});
					//window.close();
				}
			});
		}
	}//end of save

});